package com.lizk.tools.hotdeploy2.core;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 *  <p>
 * 描述：启动定时任务，定时扫描文件的变动
 * </p>
 * @author lizk
 *
 */
public class CheckFileTask implements Runnable{

	//有定时功能的线程池
	ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
	//为了在执行start方法的时候，阻塞到第一次扫描文件结束，防止启动之后立即调用类文件中的方法时出错
	CountDownLatch cdl = new CountDownLatch(1);
	
	int init = 0;
	int delay = 5;
	
	AutoExeClassCentext autoExeClassCentext = null;
	
	CheckFileTask (AutoExeClassCentext autoExeClassCentext,int init , int delay){
		this.autoExeClassCentext = autoExeClassCentext;
		this.init = init;
		this.delay = delay;
	}
	
	public void start() throws InterruptedException, ExecutionException{
		service.scheduleWithFixedDelay(this, init, delay, TimeUnit.SECONDS);
		//阻塞，得带第一次扫描结束
		cdl.await();
	}

	@Override
	public void run() {
		try {
			if (autoExeClassCentext.getCheckClassChange().checkAllFile()) {
				autoExeClassCentext.loadAllClass();
				autoExeClassCentext.getCheckClassChange().reSetIsChange();
				System.out.println("已重新加载类文件");
			}
		} catch (Exception e) {
			System.err.println("定时扫描任务已停止，" + e.getMessage());
			throw new AutoExeClassException("加载类文件失败'", e);
		} finally {
			if(cdl != null){
				//结束start方法的阻塞 
				cdl.countDown();
				//释放资源
				cdl = null;
			}
		}
	}
}
